package com.ajhlp.spring_modules.file;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

public class FileReader {
	
	private Logger log = Logger.getLogger(getClass());

	/**
	 * 从文件中获取一部分数据
	 * @param start_row 起始行（如果倒序，则为倒数行数）
	 * @param row_num 获取的总行数
	 * @param file 文件
	 * @param reverse 是否反转
	 * @return
	 */
	public String[] getLineOfFile(int start_row, int row_num, File file, boolean reverse){
		LineNumberReader lnr = null;
		
		try {
			lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"), 10*1024*1024);
			
			int totalNum = this.getFileLineNum(file);
			
			if(start_row > totalNum){
				return new String[]{};
			}
			
			List<String> strs = new ArrayList<String>();
			
			if(reverse){
				
				start_row = totalNum-start_row-1;
				
				for(int i=0;i<row_num;i++){
					lnr.setLineNumber(start_row-i);
					strs.add(lnr.readLine());
				}
				
			}else{
			
				for(int i=0;i<row_num;i++){
					lnr.setLineNumber(start_row+i);
					strs.add(lnr.readLine());
				}
			}
			return null;
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 获得文件总行数
	 * @param file
	 * @return
	 */
	public int getFileLineNum(File file){
		
		long now = System.currentTimeMillis();
		
		BufferedReader br = null;
		
		InputStreamReader is = null;
		try {
			is = new InputStreamReader(new BufferedInputStream(new FileInputStream(file), 10*1024*1024),"UTF-8");
			br = new BufferedReader(is);
			
			int num = 0;
			
			String tmp = null;
			
			while((tmp = br.readLine()) != null){
				num++;
			}
			
			return num;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			return 0;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			return 0;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return 0;
		} finally {
			try {
				br.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
			log.info("read file line num cost "+(System.currentTimeMillis()-now)+"ms");
		}
		
		
		
	}
}
